package edu.uwosh.cs342.group2.project4.database;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

abstract class ObjectDb {
	SQLiteDatabase db = null;
	private DatabaseOpenHelper databaseOpenHelper;
	Context context = null;
    private static final String DATABASE = "Project4";
    private static final String CREATE_CATEGORY =
		"CREATE TABLE IF NOT EXISTS Category (" +
		"[Id] INTEGER PRIMARY KEY AUTOINCREMENT," +
		"[Name] TEXT NOT NULL);";
    
    private static final String CREATE_LOCATION =
		"CREATE TABLE IF NOT EXISTS Location (" +
		"[Id] INTEGER PRIMARY KEY AUTOINCREMENT," +
		"[Name] TEXT NOT NULL," +
		"[Description] TEXT NOT NULL," +
		"[Longitude] REAL NOT NULL," +
		"[Latitude] REAL NOT NULL," +
		"[Location] TEXT NOT NULL," +
		"[CategoryId] INTEGER NOT NULL," +
		"FOREIGN KEY (CategoryId) REFERENCES Category (Id));";
    
    /**
     * Opens the connection to the database
     * @param context
     */
    public ObjectDb(Context context) {
    	this.context = context;
    	databaseOpenHelper = new DatabaseOpenHelper(context, DATABASE, null, 1);
    	this.OpenConnection();
    }

    /**
     * Opens the database connection
     */
    protected void OpenConnection() {
    	try {
    		this.db = databaseOpenHelper.getWritableDatabase();
    	}
    	catch (SQLException ex) {
    		Toast.makeText(this.context, ex.getMessage(), 25).show();
    	}
    }

    /**
     * Closes the connection to the database
     * Will throw an error if not connected to the database
     */
    protected void CloseConnection() {
    	if (this.db != null) {
    		this.db.close();
    	}
    }
    
    /**
     * Helper class to open the database
     * @author Drew McCauley
     *
     */
    private class DatabaseOpenHelper extends SQLiteOpenHelper {
    	public DatabaseOpenHelper(Context context, String name, CursorFactory factory, int version) {
    		super(context, name, factory, version);
    	}
    	
    	public void onCreate(SQLiteDatabase db) {
    		db.execSQL(CREATE_CATEGORY);
    		db.execSQL(CREATE_LOCATION);
    	}
    	
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		// nothing to do here -_-
    	}
    }
}
